package com.hospital.payment.module.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.hospital.payment.module.config.properties.QRCodeProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码生成器
 * @author yhn
 * @version 1.0
 */
@Component
public class QRCodeGenerator {

    @Autowired
    private QRCodeProperties qrCodeProperties;
    /**
     * 生成二维码图片字节数组
     */
    public byte[] generateQRCodeBytes() throws Exception {
        BitMatrix bitMatrix = createMatrix(qrCodeProperties.getUrl());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, qrCodeProperties.getFormat(), baos);
        return baos.toByteArray();
    }

    /**
     * 生成二维码
     */
    public BufferedImage generateQRCodeImage() throws Exception {
        BitMatrix bitMatrix = createMatrix(qrCodeProperties.getUrl());
        return MatrixToImageWriter.toBufferedImage(bitMatrix);
    }

    private BitMatrix createMatrix(String content) throws Exception {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN, 1);
        QRCodeWriter writer = new QRCodeWriter();
        return writer.encode(content, BarcodeFormat.QR_CODE, qrCodeProperties.getWidth(), qrCodeProperties.getHeight(), hints);
    }
}
